package drds.common.db.xml_mapping.parsing;

import drds.common.db.xml_mapping.builder.BuilderException;
import lombok.Getter;
import lombok.Setter;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.*;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


public class XmlNodeParser {

  @Setter
  @Getter
  private final Document document;
  @Setter
  @Getter
  private boolean validation;
  @Setter
  @Getter
  private Properties variables;
  @Setter
  @Getter
  private EntityResolver entityResolver;
  //
  @Setter
  @Getter
  private XPath xpath;

  public XmlNodeParser(String xml, boolean validation, Properties variables, EntityResolver entityResolver) {
    commonConstructor(validation, entityResolver, variables);
    this.document = createDocument(new InputSource(new StringReader(xml)));
  }

  public XmlNodeParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {
    commonConstructor(validation, entityResolver, variables);
    this.document = createDocument(new InputSource(reader));
  }

  public XmlNodeParser(InputStream inputStream, boolean validation, Properties variables, EntityResolver entityResolver) {
    commonConstructor(validation, entityResolver, variables);
    this.document = createDocument(new InputSource(inputStream));
  }

  private Document createDocument(InputSource inputSource) {
    // important: this must only be called AFTER common constructor
    try {
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      documentBuilderFactory.setValidating(validation);

      documentBuilderFactory.setNamespaceAware(false);
      documentBuilderFactory.setIgnoringComments(true);
      documentBuilderFactory.setIgnoringElementContentWhitespace(false);
      documentBuilderFactory.setCoalescing(false);
      documentBuilderFactory.setExpandEntityReferences(true);

      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      documentBuilder.setEntityResolver(entityResolver);
      documentBuilder.setErrorHandler(new ErrorHandler() {
        @Override
        public void error(SAXParseException exception) throws SAXException {
          throw exception;
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
          throw exception;
        }

        @Override
        public void warning(SAXParseException exception) throws SAXException {
        }
      });
      return documentBuilder.parse(inputSource);
    } catch (Exception e) {
      throw new BuilderException("Error creating document instance.  Cause: " + e, e);
    }
  }

  private void commonConstructor(boolean validation, EntityResolver entityResolver, Properties variables) {
    this.validation = validation;
    this.entityResolver = entityResolver;
    this.variables = variables;
    //
    XPathFactory xPathFactory = XPathFactory.newInstance();
    this.xpath = xPathFactory.newXPath();
  }

  //
  //
  public String evaluateString(String expression) {
    return evaluateString(document, expression);
  }

  public String evaluateString(Object root, String expression) {
    String result = (String) evaluate(root, expression, XPathConstants.STRING);
    result = PropertyParser.parse(result, variables);
    return result;
  }

  public Boolean evaluateBoolean(String expression) {
    return evaluateBoolean(document, expression);
  }

  public Boolean evaluateBoolean(Object root, String expression) {
    return (Boolean) evaluate(root, expression, XPathConstants.BOOLEAN);
  }

  //
  public Short evaluateShort(String expression) {
    return evaluateShort(document, expression);
  }

  public Short evaluateShort(Object root, String expression) {
    return Short.valueOf(evaluateString(root, expression));
  }

  //
  public Integer evaluateInteger(String expression) {
    return evaluateInteger(document, expression);
  }

  public Integer evaluateInteger(Object root, String expression) {
    return Integer.valueOf(evaluateString(root, expression));
  }

  public Long evaluateLong(String expression) {
    return evaluateLong(document, expression);
  }

  public Long evaluateLong(Object root, String expression) {
    return Long.valueOf(evaluateString(root, expression));
  }

  //
  public Float evaluateFloat(String expression) {
    return evaluateFloat(document, expression);
  }

  public Float evaluateFloat(Object root, String expression) {
    return Float.valueOf(evaluateString(root, expression));
  }

  //
  public Double evaluateDouble(String expression) {
    return evaluateDouble(document, expression);
  }

  public Double evaluateDouble(Object root, String expression) {
    return (Double) evaluate(root, expression, XPathConstants.NUMBER);
  }

  //
  public List<XmlNode> evaluateXmlNodeList(String expression) {
    return evaluateXmlNodeList(document, expression);
  }

  public List<XmlNode> evaluateXmlNodeList(Object root, String expression) {
    List<XmlNode> xmlNodeList = new ArrayList<>();
    NodeList nodeList = (NodeList) evaluate(root, expression, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
      xmlNodeList.add(new XmlNode(this, nodeList.item(i), variables));
    }
    return xmlNodeList;
  }

  //
  public XmlNode evaluateNode(String expression) {
    return evaluateNode(document, expression);
  }

  public XmlNode evaluateNode(Object root, String expression) {
    org.w3c.dom.Node node = (org.w3c.dom.Node) evaluate(root, expression, XPathConstants.NODE);
    if (node == null) {
      return null;
    }
    return new XmlNode(this, node, variables);
  }

  //
  private Object evaluate(Object root, String expression, QName returnType) {
    try {
      return xpath.evaluate(expression, root, returnType);
    } catch (Exception e) {
      throw new BuilderException("Error evaluating XPath.  Cause: " + e, e);
    }
  }


}
